using System;
using System.IO;
using UnityEngine;



/// <summary>
/// Asset Bundle 资源 | 助理
/// </summary>
public class AssetBundleUtil
{
    /// <summary>
    /// 加载 | 有依赖关联
    /// </summary>
    /// <param name="folderPath"></param>
    /// <param name="fileName"></param>
    /// <param name="output"></param>
    /// <returns></returns>
    public static bool TryLoadGameObject(string folderPath, string manifestRoot, string fileName, out GameObject output)
    {
        bool isExist = Directory.Exists(folderPath);
        if (!isExist)
        {
            Debug.LogWarning($"目录不存在 | {folderPath}");
            output = default;
            return false;
        }

        // 加载依赖
        AssetBundle assetBundle = AssetBundle.LoadFromFile($"{folderPath}/{manifestRoot}");
        AssetBundleManifest manifest = assetBundle.LoadAsset<AssetBundleManifest>("AssetBundleManifest");

        string[] dependencies = manifest.GetAllDependencies(fileName);
        Debug.Log($"加载依赖项 | {fileName} | {dependencies.Length}");
        if (dependencies.Length != 0)
        {
            Array.ForEach(dependencies, e => AssetBundle.LoadFromFile($"{folderPath}/{e}"));
        }


        assetBundle = AssetBundle.LoadFromFile($"{folderPath}/{fileName}");
        GameObject target = assetBundle.LoadAsset<GameObject>(fileName);
        output = GameObject.Instantiate(target);

        assetBundle.Unload(true);
        return true;
    }

    /// <summary>
    /// 加载 | 无依赖关联
    /// </summary>
    /// <param name="folderPath"></param>
    /// <param name="fileName"></param>
    /// <param name="output"></param>
    /// <returns></returns>
    public static bool TryLoadGameObject(string folderPath, string fileName, out GameObject output)
    {

        bool isExist = Directory.Exists(folderPath);
        if (!isExist)
        {
            Debug.LogWarning($"目录不存在 | {folderPath}");
            output = default;
            return false;
        }

        AssetBundle assetBundle = AssetBundle.LoadFromFile($"{folderPath}/{fileName}");
        output = assetBundle.LoadAsset<GameObject>(fileName);

        if (!output)
        {
            UnityEngine.Debug.LogError($"资源不存在 | {folderPath}/{fileName}");
            return false;
        }

        //assetBundle.Unload(true);
        return true;
    }
}
